<template>
  <div class="app-container">
    <el-row :gutter="0">
      <el-col :span="7">
        <div style="margin-right: 8px">
          <div style="margin-bottom: 10px">
            <el-button-group>
              <el-button
                icon="el-icon-plus"
                type="primary"
                @click="showAddLinkage"
              />
              <el-button
                icon="el-icon-s-order"
                type="primary"
                @click="showExecute()"
              />
              <el-button
                icon="el-icon-delete"
                type="danger"
                @click="deleteLinkageByDeviceToDevice"
              />
            </el-button-group>
          </div>
          <div>
            <div v-for="(item,index) in linkageList" :key="item.linkageTag" @click="linkageChange(item)">
              <div :class="[{well:item.linkageTag === linkage.linkageTag}]" style="padding: 8px" class="item">
                <div style="display: flex;justify-content: space-between;">
                  <div style="font-size: 13px;color: #707e7f;font-weight: bold;line-height: 30px" @click="edit(item)">
                    <i :class="item.type==='server' ? 'el-icon-cloudy' : 'el-icon-cpu'" />
                    {{ item.name }}
                  </div>
                  <div>
                    <el-tag
                      style="margin-right: 10px"
                      :type="1 === item.status ? 'success' : 'danger'"
                      @click="updateLinkageStatusToDevice(item)"
                      v-text="1 === item.status ? $t('enable'):$t('DISABLE')"
                    />
                    <el-button
                      icon="el-icon-date"
                      type="text"
                      style="color: #707e7f"
                      @click="showExecute(item.linkageId)"
                    />
                    <el-button
                      icon="el-icon-delete"
                      type="text"
                      style="color: #FF805F"
                      @click="deleteLinkageToDevice(item)"
                    />
                  </div>
                </div>
                <div style="display: flex;justify-content: flex-end;margin-top: 10px">
                  <el-date-picker
                    v-model="item.startDate"
                    style="width: 180px;margin-right: 2px"
                    type="datetime"
                    :placeholder="$t('startDate')"
                    align="right"
                    :picker-options="pickerOptions1"
                    value-format="timestamp"
                    @blur="linkageTimeChange(item)"
                  />
                  <el-date-picker
                    v-model="item.endDate"
                    style="width: 180px;margin-right: 2px"
                    type="datetime"
                    :placeholder="$t('endDate')"
                    align="right"
                    :picker-options="pickerOptions1"
                    value-format="timestamp"
                    @blur="linkageTimeChange(item)"
                  />
                  <el-button
                    v-if="item.timeChange"
                    type="primary"
                    icon="el-icon-check"
                    @click="updateLinkageTimeToDevice(item)"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="17">
        <div
          style="height: calc(100vh - 120px)"
          class="uni-scroll"
        >
          <trigger v-if="linkage.linkageId" :linkage="linkage" />
          <condition
            v-if="linkage.linkageId"
            style="margin-top: 10px"
            :linkage="linkage"
          />
          <setting
            v-if="linkage.linkageId"
            style="margin-top: 10px"
            :linkage="linkage"
          />
        </div>
      </el-col>
    </el-row>

    <el-dialog
      :visible.sync="linkageDialogVisible"
    >
      <el-form
        label-width="20%"
      >
        <el-form-item :label="$t('name')">
          <el-input v-model="linkage.name" />
        </el-form-item>
        <el-form-item :label="$t('keyName')">
          <el-input v-model="linkage.linkageTag" disabled />
        </el-form-item>
        <el-form-item :label="$t('type')">
          <el-select
            v-model="linkage.type"
            clearable
            filterable
            :disabled="linkage.linkageId"
            @change="formTypeChange"
          >
            <el-option :label="$t('device')" value="device" :disabled="!device.canDeviceLinkage" />
            <el-option :label="$t('server')" value="server" :disabled="!enableServerLinkage" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!linkage.linkageId" :label="$t('startDate')">
          <el-date-picker
            v-model="linkage.startDate"
            type="datetime"
            :placeholder="$t('startDate')"
            align="right"
            :picker-options="pickerOptions1"
            value-format="timestamp"
          />
        </el-form-item>
        <el-form-item v-if="!linkage.linkageId" :label="$t('endDate')">
          <el-date-picker
            v-model="linkage.endDate"
            type="datetime"
            :placeholder="$t('startDate')"
            align="right"
            :picker-options="pickerOptions1"
            value-format="timestamp"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="linkageDialogVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdateLinkage">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  cancelNotice,
  failureNotice,
  successNotice
} from '@/util/common'
import {
  deleteLinkageByDeviceToDevice,
  deleteLinkageByDeviceToServer,
  deleteLinkageToDevice,
  deleteLinkageToServer,
  insertLinkageToDevice,
  insertLinkageToServer,
  listLinkage,
  updateLinkage,
  updateLinkageToDevice,
  updateLinkageToServer
} from '@/api/iot/iotDeviceLinkageApi'
import { getDevice } from '@/api/iot/iotDeviceApi'
import Condition from './Condition'
import Setting from './Setting'
import Trigger from './Trigger'
import { getEnableServerLinkage } from '@/util/storage'

export default {
  name: 'Linkage',
  components: {
    Condition,
    Setting,
    Trigger
  },
  data() {
    return {
      device: {},
      linkageDialogVisible: false,
      deviceCore: null,
      linkage: {
        linkageId: null,
        name: null,
        type: null
      },
      linkageList: [],
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      enableServerLinkage: getEnableServerLinkage() === 'true'
    }
  },
  mounted() {
    const param = this.$route.query
    this.deviceCore = param.deviceCore
    if (!this.deviceCore) {
      return
    }
    this.getDevice()
  },
  methods: {
    getDevice() {
      getDevice({
        deviceCore: this.deviceCore
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.device = data
          this.setTagsViewTitle()
          this.listLinkage()
        }
      })
    },
    linkageTimeChange(item) {
      for (let i = 0, j = this.linkageList.length; i < j; i++) {
        if (item.linkageId === this.linkageList[i].linkageId) {
          item.timeChange = true
          this.linkageList.splice(i, 1, item)
        }
      }
    },
    updateLinkageStatusToDevice(item) {
      const that = this
      this.$confirm(this.$t('change') + this.$t('status'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          if (that.linkage.type === 'device') {
            updateLinkageToDevice({
              linkageId: item.linkageId,
              status: item.status === 1 ? 0 : 1
            }).then(res => {
              const { code } = res
              if (code === '200') {
                that.listLinkage()
                successNotice(that)
              }
            })
          } else if (that.linkage.type === 'server') {
            updateLinkageToServer({
              linkageId: item.linkageId,
              status: item.status === 1 ? 0 : 1
            }).then(res => {
              const { code } = res
              if (code === '200') {
                that.listLinkage()
                successNotice(that)
              }
            })
          } else {
            failureNotice(that, that.$t('type'))
            return
          }
        })
    },
    updateLinkageTimeToDevice(item) {
      if (this.linkage.type === 'device') {
        updateLinkageToDevice({
          linkageId: item.linkageId,
          startDate: item.startDate && item.startDate !== 0 ? item.startDate / 1000 : null,
          endDate: item.endDate && item.endDate !== 0 ? item.endDate / 1000 : null
        }).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
          }
          this.listLinkage()
        })
      } else if (this.linkage.type === 'server') {
        updateLinkageToServer({
          linkageId: item.linkageId,
          startDate: item.startDate && item.startDate !== 0 ? item.startDate / 1000 : null,
          endDate: item.endDate && item.endDate !== 0 ? item.endDate / 1000 : null
        }).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
          }
          this.listLinkage()
        })
      } else {
        failureNotice(this, this.$t('type'))
        return
      }
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.device.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    showExecute(linkageId) {
      this.$router.push({
        path: '/device/linkage/execute/' + this.deviceCore,
        query: {
          deviceCore: this.deviceCore,
          deviceName: this.device.deviceName,
          linkageId: linkageId
        }
      })
    },
    linkageChange(item) {
      if (item != null) {
        this.linkage = item
      }
    },
    formTypeChange(value) {
      this.linkage.type = value
    },
    edit(item) {
      this.linkage = item
      this.linkageDialogVisible = true
    },
    deleteLinkageToDevice(item) {
      const that = this
      this.$confirm(this.$t('delete') + item.name, {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          if (that.linkage.type === 'device') {
            deleteLinkageToDevice({
              linkageId: item.linkageId
            }).then(res => {
              const { code } = res
              if (code === '200') {
                successNotice(that)
                that.listLinkage()
              }
            })
          } else if (that.linkage.type === 'server') {
            deleteLinkageToServer({
              linkageId: item.linkageId
            }).then(res => {
              const { code } = res
              if (code === '200') {
                successNotice(that)
                that.listLinkage()
              }
            })
          } else {
            failureNotice(that, that.$t('type'))
            return
          }
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    deleteLinkageByDeviceToDevice() {
      const that = this
      this.$confirm(this.$t('delete') + this.deviceCore, {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteLinkageByDeviceToServer({
            deviceCore: that.deviceCore
          }).then(() => {
            if (that.device.canDeviceLinkage) {
              deleteLinkageByDeviceToDevice({
                deviceCore: that.deviceCore
              }).then(res => {
                const { code } = res
                if (code === '200') {
                  successNotice(that)
                  that.listLinkage()
                }
              })
            } else {
              successNotice(that)
              that.listLinkage()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    listLinkage() {
      listLinkage({
        deviceCore: this.deviceCore
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const linkageList = []
          data.forEach(linkage => {
            if (linkage.startDate !== 0) {
              linkage.startDate = linkage.startDate * 1000
            }
            if (linkage.endDate !== 0) {
              linkage.endDate = linkage.endDate * 1000
            }
            linkageList.push(linkage)
          })
          if (linkageList.length > 0) {
            this.linkage = linkageList[0]
          }
          this.linkageList = linkageList
        } else {
          this.linkageList = []
        }
      })
    },
    showAddLinkage() {
      this.linkage = {
        name: '',
        type: ''
      }
      this.linkageDialogVisible = true
    },
    addOrUpdateLinkage() {
      if (this.linkage.name === '') {
        failureNotice(this, this.$t('name'))
        return
      }
      if (this.linkage.type == null || this.linkage.type === '') {
        failureNotice(this, this.$t('type'))
        return
      }
      const json = {
        type: this.linkage.type,
        name: this.linkage.name,
        deviceCore: this.deviceCore
      }

      if (!this.linkage.linkageId) {
        json.startDate = this.linkage.startDate / 1000
        json.endDate = this.linkage.endDate / 1000
        json.status = 1
        if (this.linkage.type === 'device') {
          insertLinkageToDevice(json).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(this)
              this.linkageDialogVisible = false
            }
            this.listLinkage()
          })
        } else if (this.linkage.type === 'server') {
          insertLinkageToServer(json).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(this)
              this.linkageDialogVisible = false
            }
            this.listLinkage()
          })
        } else {
          failureNotice(this, this.$t('type'))
          return
        }
      } else {
        json.linkageId = this.linkage.linkageId
        updateLinkage(json).then(res => {
          const { code } = res
          if (code === '200') {
            successNotice(this)
            this.linkageDialogVisible = false
            this.listLinkage()
          }
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
  @import '@/styles/element-variables.scss';

  .well {
    background-color: $--color-primary;
  }

  .item {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    margin-bottom: 8px;
  }

  .item:hover {
    background: #EBEEF5;
    border-radius: 6px;
  }
</style>
